import axios from 'axios';

export interface DeepSeekMessage {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

export interface DeepSeekRequest {
  model: string;
  messages: DeepSeekMessage[];
  stream: boolean;
  max_tokens?: number;
  temperature?: number;
}

export interface DeepSeekResponse {
  id: string;
  object: string;
  created: number;
  model: string;
  choices: Array<{
    index: number;
    message: DeepSeekMessage;
    finish_reason: string;
  }>;
  usage: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}

export class DeepSeekService {
  private apiKey: string;
  private apiUrl: string;

  constructor() {
    this.apiKey = process.env.DEEPSEEK_API_KEY || 'sk-9e3ffb0a2c2e4ac8bc82088081214f80';
    this.apiUrl = process.env.DEEPSEEK_API_URL || 'https://api.deepseek.com/v1/chat/completions';
    
    if (!this.apiKey) {
      throw new Error('DEEPSEEK_API_KEY 环境变量未设置');
    }
  }

  /**
   * 流式调用DeepSeek API
   * @param content 用户输入的文案
   * @param onData 数据回调函数
   * @param onError 错误回调函数
   * @param onEnd 结束回调函数
   */
  async streamChat(
    content: string,
    onData: (chunk: string) => void,
    onError: (error: Error) => void,
    onEnd: () => void
  ): Promise<void> {
    try {
      const requestData: DeepSeekRequest = {
        model: 'deepseek-chat',
        messages: [
          {
            role: 'user',
            content: content
          }
        ],
        stream: true,
        max_tokens: 4000,
        temperature: 0.7
      };

      const response = await axios({
        method: 'post',
        url: this.apiUrl,
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json',
        },
        data: requestData,
        responseType: 'stream'
      });

      response.data.on('data', (chunk: Buffer) => {
        const lines = chunk.toString().split('\n');
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6).trim();
            
            if (data === '[DONE]') {
              onEnd();
              return;
            }
            
            try {
              const parsed = JSON.parse(data);
              const content = parsed.choices?.[0]?.delta?.content;
              if (content) {
                onData(content);
              }
            } catch (e) {
              // 忽略解析错误的数据块
            }
          }
        }
      });

      response.data.on('error', (error: Error) => {
        onError(error);
      });

    } catch (error: any) {
      onError(new Error(`DeepSeek API 调用失败: ${error.message}`));
    }
  }

  /**
   * 非流式调用DeepSeek API
   * @param content 用户输入的文案
   */
  async chat(content: string): Promise<string> {
    try {
      const requestData: DeepSeekRequest = {
        model: 'deepseek-chat',
        messages: [
          {
            role: 'user',
            content: content
          }
        ],
        stream: false,
        max_tokens: 4000,
        temperature: 0.7
      };

      const response = await axios.post<DeepSeekResponse>(
        this.apiUrl,
        requestData,
        {
          headers: {
            'Authorization': `Bearer ${this.apiKey}`,
            'Content-Type': 'application/json',
          },
        }
      );

      return response.data.choices[0]?.message?.content || '没有收到有效响应';
    } catch (error: any) {
      throw new Error(`DeepSeek API 调用失败: ${error.message}`);
    }
  }
} 